package services

import (
	"gorm.io/gorm"
	"news/pkg/models"
	"news/pkg/types"
	"news/pkg/types/errors"
)

func GetSensitiveWord(db *gorm.DB, cond models.Sensitive) (*models.Sensitive, error) {
	word := models.Sensitive{}
	if err := db.Model(&models.Sensitive{}).Where(&cond).First(&word).Error; err != nil {
		if errors.IsNotFoundErr(err) {
			return nil, nil
		}
		return nil, errors.AutoDbErr(err)
	}
	return &word, nil
}

func GetSensitiveByWord(db *gorm.DB, word string) (*models.Sensitive, error) {
	sens := models.Sensitive{}
	sens.Word = word
	return GetSensitiveWord(db, sens)
}

func GetSensitiveById(db *gorm.DB, id models.Id) (*models.Sensitive, error) {
	sens := models.Sensitive{}
	sens.Id = id
	return GetSensitiveWord(db, sens)
}

func CreateSensitive(db *gorm.DB, form *types.AddSensitiveWordForm) (*models.Sensitive, error) {
	sens := models.Sensitive{
		Word:  form.Word,
		Level: form.Level,
		State: form.State,
	}
	if err := db.Model(&models.Sensitive{}).Create(&sens).Error; err != nil {
		return nil, errors.AutoDbErr(err)
	}
	return &sens, nil
}

func UpdateSensitive(db *gorm.DB, form *types.UpdateSensForm) (*models.Sensitive, error) {
	sens := models.Sensitive{}
	if form.Word != "" {
		sens.Word = form.Word
	}
	if form.Level != "" {
		sens.Level = form.Level
	}
	if form.State != "" {
		sens.State = form.State
	}
	if err := db.Model(&models.Sensitive{}).Where("id", form.Id).Updates(&sens).Error; err != nil {
		return nil, errors.AutoDbErr(err)
	}
	return GetSensitiveById(db, form.Id)
}

func DeleteSensById(db *gorm.DB, id models.Id) error {
	return db.Where("id", id).Delete(&models.Sensitive{}).Error
}

func DeleteSensByIds(db *gorm.DB, ids []models.Id) error {
	return db.Where(ids).Delete(&models.Sensitive{}).Error
}

func QuerySensWords(db *gorm.DB, form *types.QuerySensWordForm) *gorm.DB {
	sens := models.Sensitive{}
	if form.Level != "" {
		sens.Level = form.Level
	}
	if form.State != "" {
		sens.State = form.State
	}
	return db.Model(&models.Sensitive{}).Where(&models.Sensitive{}).Where("word LIKE ?", "%"+form.Q+"%").Where(&sens).Order("updated_at")
}
